import base64
import copy
import hashlib
import json
from datetime import datetime, timedelta

from apps.settingApi.api.chart.model import chartModel
from apps.settingApi.api.funs.model import funsModel
from apps.settingApi.api.basic.model import basicTypeModel
from apps.settingApi.api.printCode.model import printOrderModel
from apps.settingApi.api.timerTask.model import timerTaskConfigModel, timerTaskModel
from apps.settingApi.api.timerTask.task import add_task
from apps.settingApi.permission import barList, permissionDict1
from apps.settingApi.switchCase.casePrimaryKey import caseGetPrimaryKeyData
from apps.settingApi.api.users.model import usersModel, permissionModel, onLineModel
from apps.settingApi.api.lessees.model import lesseesModel
from comm.const import CHART01


# MD5加密
def userHashlib(data):
    """
    :param data: 需要加密的字符
    :return: 返回h5加密结果
    """
    # 创建一个 MD5 对象
    md5_hash = hashlib.md5()

    # 更新要加密的字符串
    md5_hash.update(str(data).encode('utf-8'))

    # 获取加密后的结果
    encrypted_string = md5_hash.hexdigest()
    return encrypted_string


# base64加密
def base64Jia(data):
    return base64.b64encode(str(data).encode()).decode()


# base64解密
def base64Jie(data):
    return base64.b64decode(data.encode()).decode()


# 初始化创建经销商以及用户
def userAddData(db):
    """
    用户基础资料新增
    :param db:
    :return:
    """
    # 获取当前日期
    current_date = datetime.now()
    # 将年份加100
    future_date = current_date + timedelta(days=100 * 365)
    # 创建经销商租户
    obj1 = lesseesModel.query.filter_by(id="000001").first()
    if obj1 is None:
        dataObj = {}
        dataObj["id"] = "000001"
        dataObj["name"] = "经销商"
        dataObj["type"] = 1
        dataObj["create_user"] = "root"
        dataObj["create_user"] = "root"
        dataObj['end_time'] = future_date
        lessees = lesseesModel(**dataObj)
        db.session.add(lessees)
        db.session.commit()
    # 创建经销商管理员账号
    obj1 = usersModel.query.filter_by(username="root").first()
    if obj1 is None:
        dataObj = {}
        id_z = caseGetPrimaryKeyData()
        dataObj["id"] = id_z
        dataObj["code"] = "root"
        dataObj["username"] = "root"
        dataObj["lessees_id"] = "000001"
        # dataObj["password"] = userHashlib('root')
        dataObj["password"] = base64Jia('root')
        dataObj["type"] = 1
        dataObj["create_user"] = id_z
        dataObj['end_time'] = future_date
        user = usersModel(**dataObj)
        db.session.add(user)
        db.session.commit()
    return


# 初始化创建菜单
def barAddData(db):
    barAddList = barList()
    barAddDataList = []
    for itm1 in barAddList:
        exit_id1 = db.session.query(funsModel).filter(funsModel.id == itm1['id']).first()
        if exit_id1 is None:
            itm1_z = copy.deepcopy(itm1)
            del itm1_z['children']
            barAddDataList.append(funsModel(**itm1_z))
        if len(itm1['children']) > 0:
            for itm2 in itm1['children']:
                exit_id2 = db.session.query(funsModel).filter(funsModel.id == itm2['id']).first()
                if exit_id2 is None:
                    del itm2['children']
                    itm2['parent_code'] = itm1['code']
                    barAddDataList.append(funsModel(**itm2))
    db.session.add_all(barAddDataList)
    db.session.commit()


# 创建基础权限选项
def permissionAddData(db):
    permissionDictData = permissionDict1()
    permissionAddDataList = []
    for itm1 in permissionDictData.keys():
        for itm2 in permissionDictData[itm1]['list']:
            permissionObj = {}
            permissionObj['funs_code'] = permissionDictData[itm1]['funs_code']
            permissionObj['name'] = permissionDictData[itm1]['name'] + '-' + itm2['name']
            permissionObj['code'] = itm1 + '-' + itm2['method']
            permissionObj['status'] = 1
            permissionObj['id'] = caseGetPrimaryKeyData()
            exit_id = db.session.query(permissionModel).filter(permissionModel.code == permissionObj['code']).first()
            if exit_id is None:
                permissionAddDataList.append(permissionModel(**permissionObj))
    db.session.add_all(permissionAddDataList)
    db.session.commit()


# 基础数据类型增加
def basicTypeAddData(db):
    basicTypeDictData = [
        {
            "id": "2024053114505639250008001",
            "label": "部门资料",
            "value": "dept",
            "sort": "10",
            "status": True,
        },
        {
            "id": "2024053114505639250008002",
            "label": "员工资料",
            "value": "salm",
            "sort": "20",
            "status": True,
        },
        {
            "id": "2024053114505639250008003",
            "label": "货品资料",
            "value": "prdt",
            "sort": "30",
            "status": True,
        },
        {
            "id": "2024053114505639250008004",
            "label": "数据库",
            "value": "dbpool",
            "sort": "30",
            "status": True,
        }
    ]
    basicTypeAddDataList = []
    for itm1 in basicTypeDictData:

        exit_id = db.session.query(basicTypeModel).filter(basicTypeModel.id == itm1['id']).first()
        if exit_id is None:
            basicTypeAddDataList.append(basicTypeModel(**itm1))
    db.session.add_all(basicTypeAddDataList)
    db.session.commit()


def printOrderAddData(db):
    printOrderDictData = [
        {
            "id": "2024053114505639250008001",
            "name": "部门资料",
            "code": "dept",
        },
        {
            "id": "2024053114505639250008002",
            "name": "员工资料",
            "code": "salm",
        },
        {
            "id": "2024053114505639250008003",
            "name": "货品资料",
            "code": "prdt",
        }
    ]
    printOrderAddDataList = []
    for itm1 in printOrderDictData:

        exit_id = db.session.query(printOrderModel).filter(printOrderModel.code == itm1['code']).first()
        if exit_id is None:
            itm1['id'] = caseGetPrimaryKeyData()
            printOrderAddDataList.append(printOrderModel(**itm1))
    db.session.add_all(printOrderAddDataList)
    db.session.commit()


# 程序启动时候删除全部在线用户
def onLineModelDelete(db):
    onLineModel.query.filter().delete()
    db.session.commit()


# 定时任务配置
def timerTaskConfigModelAdd(db):
    # 查询定时器配置是否存在
    exit_id = db.session.query(timerTaskConfigModel).filter(
        timerTaskConfigModel.id == '2024053114505639250008110').first()
    if exit_id is None:
        timerTaskConfig = {}
        timerTaskConfig["id"] = '2024053114505639250008110'
        timerTaskConfig["time"] = 5
        timerTaskConfig["status"] = True
        jobId = add_task(trigger='interval', seconds=5)
        timerTaskConfig["process"] = jobId
        db.session.add(timerTaskConfigModel(**timerTaskConfig))
        db.session.commit()
    # # 如果存在启动定时器
    # if exit_id != None:
    #     if exit_id.status == True:
    #         jobId = add_task(trigger='interval', seconds=exit_id.time)
    #         db.session.query(timerTaskConfigModel).filter().update(
    #             {"status": True, "process": jobId})
    #         db.session.commit()


def timerTaskModelAdd(db):
    addDataList = [
        {
            "id": "2024053114505639250008110",
            "name": "货品资料",
            "type": "u9capi",
            "code": "u9capiPrdt",
            "order_type": 1,
            "status": False,
            "sort": 10,
            "rem": "U9C→WMS：读取料品资料推送到WMS货品资料"
        },
        {
            "id": "2024053114505639250008111",
            "name": "中类资料",
            "type": "u9capi",
            "code": "u9capiIdx",
            "order_type": 1,
            "status": False,
            "sort": 10,
            "rem": "U9C→WMS：读取产品分类推送到WMS中类资料"
        },{
            "id": "2024053114505639260000025",
            "name": "存储地点",
            "type": "u9capi",
            # "code": "u9capiCoom",
            "code": "u9capiWh",
            "order_type": 1,
            "status": False,
            "sort": 10,
            "rem": "U9C→WMS：读取存储地点推送到WMS仓库资料"
        },
        #     {
        #     "id": "2024053114505639250008112",
        #     "name": "库位资料",
        #     "type": "u9capi",
        #     "code": "u9capiWh",
        #     "order_type": 1,
        #     "status": 0,
        #     "rem": "WMS方调取ERP方基础资料"
        # },
        #     {
    #         "id": "2024053114505639250008113",
    #         "name": "储位资料",
    #         "type": "u9capi",
    #         "code": "u9capiCoom",
    #         # "code": "u9capiCw",
    #         "order_type": 1,
    #         "status": 0,
    #         "rem": "WMS方调取ERP方基础资料"
    #     },
            {
            "id": "2024053114505639250008114",
            "name": "部门资料",
            "type": "u9capi",
            "code": "u9capiDept",
            # "code": "u9capiDept",
            "order_type": 1,
            "status": False,
            "sort": 10,
            "rem": "U9C→WMS：读取部门推送到WMS部门资料"
        },
        #     {
    #         "id": "2024053114505639250008115",
    #         "name": "业务员资料",
    #         "type": "u9capi",
    #         "code": "u9capiCoom",
    #         # "code": "u9capiSalm",
    #         "order_type": 1,
    #         "status": 0,
    #         "rem": "WMS方调取ERP方基础资料"
    #     },
    # {
    #     "id": "2024053114505639260000001",
    #     "name": "采购送检",
    #     "type": "u9capi",
    #     "code": "u9capiCoom",
    #     # "code": "u9capiPoTi",
    #     "order_type": 2,
    #     "status": 0,
    #     "rem": "WMS方调取ERP方基础资料"
    # },
        {
            "id": "2024053114505639260000002",
            "name": "标准收货直接入库",
            "type": "u9capi",
            # "code": "u9capiCoom",
            # "code": "u9capiPoTi",
            "code": "u9capiPoYsRk",
            "order_type": 2,
            "status": False,
            "sort": 20,
            "rem": "U9C→WMS：读取标准收货推送到WMS入库通知单（01）"
        },
        {
            "id": "2024053114505639260000024",
            "name": "提交并审核标准收货单行",
            "type": "u9capi",
            # "code": "u9capiCoom",
            "code": "wmsapiPullU9cShBiaoZhunShouHuoRow",
            "order_type": 2,
            "status": False,
            "sort": 30,
            "rem": "WMS→U9C：读取入库通知单（01）表身已入库完成的行调用U9C的标准收货单进行行提交及行审核"
        },

        {
            "id": "2024053114505639260000004",
            "name": "领料申请",
            "type": "u9capi",
            # "code": "u9capiCoom",
            "code": "u9capiMlSq",
            "order_type": 4,
            "status": False,
            "sort": 40,
            "rem": "U9C→WMS：读取领料申请单推送到WMS出库通知单（05）"
        },
        {
            "id": "2024053114505639260000005",
            "name": "生产退料申请",
            "type": "u9capi",
            # "code": "u9capiCoom",
            "code": "u9capiMlSqTl",
            "order_type": 2,
            "status": False,
            "sort": 50,
            "rem": "U9C→WMS：读取生产退料申请单推送到WMS入库通知单（06）"
        },
        {
            "id": "2024053114505639260000007",
            "name": "材料出库",
            "type": "u9capi",
            # "code": "u9capiCoom",
            "code": "wmsapiPullU9cClMfCk",
            "order_type": 2,
            "status": False,
            "sort": 60,
            "rem": "WMS→U9C：读取出库单（05）调用U9C的材料出库单新增并且审核"
        },
        {
            "id": "2024053114505639260000008",
            "name": "材料入库",
            "type": "u9capi",
            # "code": "u9capiCoom",
            "code": "wmsapiPullU9cClMfRk",
            "order_type": 2,
            "status": False,
            "sort": 70,
            "rem": "WMS→U9C：读取入库单（06）调用U9C的材料入库单新增并且审核"
        },

        {
            "id": "2024053114505639260000003",
            "name": "出货计划",
            "type": "u9capi",
            # "code": "u9capiCoom",
            "code": "u9capiCk",
            "order_type": 3,
            "status": False,
            "sort": 20,
            "rem": "WMS方调取ERP方出货计划"
        },
        # {
        #     "id": "2024053114505639260000006",
        #     "name": "生产领料",
        #     "type": "u9capi",
        #     # "code": "u9capiCoom",
        #     "code": "wmsapiPullU9cMlMfCk",
        #     "order_type": 2,
        #     "status": 50,
        #     "rem": "WMS推送领料出库至u9c生成领料单"
        # },
        {
            "id": "2024053114505639260000009",
            "name": "退货申请单",
            "type": "u9capi",
            # "code": "u9capiCoom",
            "code": "u9capiPoTh",
            "order_type": 2,
            "status": False,
            "sort": 70,
            "rem": "WMS方调取u9c原材料进货退货申请单生成进货回退出库通知单"
        },
        {
            "id": "2024053114505639260000010",
            "name": "退回处理",
            "type": "u9capi",
            # "code": "u9capiCoom",
            "code": "u9capiSaTh",
            "order_type": 2,
            "status": False,
            "sort": 80,
            "rem": "WMS方调取u9c退回处理生成销货退回入库通知单"
        },
        # {
        #     "id": "2024053114505639260000011",
        #     "name": "废品处理",
        #     "type": "u9capi",
        #     # "code": "u9capiCoom",
        #     "code": "u9capiFpCl",
        #     "order_type": 2,
        #     "status": False,
        #     "sort": 90,
        #     "rem": "WMS方调取u9c废品处理（杂发单单据类型为）生成出库通知单"
        # },
        {
            "id": "2024053114505639260000012",
            "name": "杂发单",
            "type": "u9capi",
            # "code": "u9capiCoom",
            "code": "u9capiZfCk",
            "order_type": 2,
            "status": False,
            "sort": 100,
            "rem": "WMS方调取u9c杂发单生成出库通知单"
        },
        {
            "id": "2024053114505639260000013",
            "name": "杂收单",
            "type": "u9capi",
            # "code": "u9capiCoom",
            "code": "u9capiZsRk",
            "order_type": 2,
            "status": False,
            "sort": 110,
            "rem": "WMS方调取u9c杂收单生成入库通知单"
        },
        {
            "id": "2024053114505639260000014",
            "name": "调入单",
            "type": "u9capi",
            # "code": "u9capiCoom",
            "code": "u9capiDbRk",
            "order_type": 2,
            "status": False,
            "sort": 120,
            "rem": "WMS方调取u9c调入单生调拨通知单排除单据类似为WWFL001的单"
        },
        {
            "id": "2024053114505639260000015",
            "name": "杂收单审核",
            "type": "u9capi",
            # "code": "u9capiCoom",
            "code": "wmsapiPullU9cZsSh",
            "order_type": 2,
            "status": False,
            "sort": 130,
            "rem": "读取WMS的入库通知单单据类型为其他入库单且是已经结案的单，关联u9c的杂收单进行审核"
        },
        {
            "id": "2024053114505639260000016",
            "name": "杂发单审核",
            "type": "u9capi",
            # "code": "u9capiCoom",
            "code": "wmsapiPullU9cZfSh",
            "order_type": 2,
            "status": False,
            "sort": 140,
            "rem": "读取WMS的出库通知单单据类型为其他出库单且是已经结案的单，关联u9c的杂发单进行审核"
        },
        {
            "id": "2024053114505639260000017",
            "name": "新增杂收单并审核",
            "type": "u9capi",
            # "code": "u9capiCoom",
            "code": "wmsapiPullU9cZsShMfRk",
            "order_type": 2,
            "status": False,
            "sort": 150,
            "rem": "读取WMS的入库单库位类型为12库存入库的出库单，推送至u9c生成杂收单并审核"
        },
        {
            "id": "2024053114505639260000018",
            "name": "新增杂发单并审核",
            "type": "u9capi",
            # "code": "u9capiCoom",
            "code": "wmsapiPullU9cZfShMfCk",
            "order_type": 2,
            "status": False,
            "sort": 160,
            "rem": "读取WMS的出库单库位类型为17库存出库的出库单，推送至u9c生成杂发单并审核"
        },
        {
            "id": "2024053114505639260000019",
            "name": "成品入库",
            "type": "u9capi",
            # "code": "u9capiCoom",
            "code": "u9capiCpRk",
            "order_type": 2,
            "status": False,
            "sort": 170,
            "rem": "读取u9c的未审核状态的成品入库单推送至wms生成入库通知单04成品入库类型的单据"
        },{
            "id": "2024053114505639260000026",
            "name": "审核成品入库单",
            "type": "u9capi",
            # "code": "u9capiCoom",
            "code": "wmsapiPullU9cMmSh",
            "order_type": 2,
            "status": False,
            "sort": 171,
            "rem": "读取wms入库通知单业务类型为04的表身行当行全部入库完成时审核u9c成品收货单"
        },
        # {
        #     "id": "2024053114505639260000020",
        #     "name": "标准收货检验入库",
        #     "type": "u9capi",
        #     # "code": "u9capiCoom",
        #     "code": "u9capiPoYsRk",
        #     "order_type": 2,
        #     "status": 0,
        #     "rem": "读取u9c的标准收货单收货程序为收货到检验到入库对应字段RcvProcedure为2且实收数量+退补数量+退扣数量大于等于点收数量且状态为检验完成对应字段Status为2时候的数据推送到wms生成入库通知到业务类型为01"
        # },
        {
            "id": "2024053114505639260000021",
            "name": "退货单",
            "type": "u9capi",
            # "code": "u9capiCoom",
            "code": "wmsapiPullU9cPoMfCk",
            "order_type": 2,
            "status": False,
            "sort": 200,
            "rem": "读取wms的出库单业务类型为02的进货退回单推送至u9c生成退货单"
        },
        {
            "id": "2024053114505639260000022",
            "name": "销货出库有来源单",
            "type": "u9capi",
            # "code": "u9capiCoom",
            "code": "wmsapiPullU9cSaMfPSS",
            "order_type": 2,
            "status": False,
            "sort": 210,
            "rem": "读取wms的出库单业务类型为01的销货出库单推送至u9c生成标准出库单"
        },
        {
            "id": "2024053114505639260000023",
            "name": "销售退回收货单有来源单",
            "type": "u9capi",
            # "code": "u9capiCoom",
            "code": "wmsapiPullU9cSbMfPss",
            "order_type": 2,
            "status": False,
            "sort": 220,
            "rem": "读取wms的入库单业务类型为03的销货退回推送至u9c生成销售退回收货单"
        },

        {
            "id": "2024053114505639260000027",
            "name": "审核调入单",
            "type": "u9capi",
            # "code": "u9capiCoom",
            "code": "wmsapiPullU9cCkDb",
            "order_type": 2,
            "status": False,
            "sort": 240,
            "rem": "读取wms调拨通知单业务类型为17的单据全部出完的单据查询出来审核u9c的调入单"
        },{
            "id": "2024053114505639260000028",
            "name": "托工领料",
            "type": "u9capi",
            # "code": "u9capiCoom",
            "code": "u9capiTwDbCk",
            "order_type": 2,
            "status": False,
            "sort": 250,
            "rem": "读取u9c调入单单据类型为WWFL001的单据推送到wms生成调拨通知单业务类型为07"
        },{
            "id": "2024053114505639260000029",
            "name": "报废处理",
            "type": "u9capi",
            # "code": "u9capiCoom",
            "code": "u9capiFpZfCk",
            "order_type": 2,
            "status": False,
            "sort": 260,
            "rem": "读取u9c杂发单单据类型为FPCL001未审核的单据推送到wms生成出库通知单业务类型为12报废出库单"
        },{
            "id": "2024053114505639260000030",
            "name": "托工入库",
            "type": "u9capi",
            # "code": "u9capiCoom",
            "code": "u9capiWtRk",
            "order_type": 2,
            "status": False,
            "sort": 270,
            "rem": "读取u9c形态转换单单据类型为WWRK001未审核的单据推送到wms生成入库通知单业务类型为05托外加工入库"
        },{
            "id": "2024053114505639260000031",
            "name": "托工入库审核",
            "type": "u9capi",
            # "code": "u9capiCoom",
            "code": "wmsapiPullU9cTwMmSh",
            "order_type": 2,
            "status": False,
            "sort": 280,
            "rem": "读取wms入库通知单单据类型为05的托工入库单审核u9c的形态转换单"
        },
        {
        "id": "2024053114505639260000032",
        "name": "盘点差异单",
        "type": "u9capi",
        # "code": "u9capiCoom",
        "code": "wmsapiPullU9cPanYingKui",
        "order_type": 2,
        "status": False,
        "sort": 290,
        "rem": "读取wms盘盈盘亏单推送至u9c生成差异调整单"
    }
    ]

    for itm in addDataList:

        # 查询定时器配置是否存在
        exit_id = db.session.query(timerTaskModel).filter(
            timerTaskModel.id == itm["id"]).first()
        if exit_id is None:
            db.session.add(timerTaskModel(**itm))
            db.session.commit()

# 看板模板
def chartModelAdd(db):
    # 查询定时器配置是否存在
    exit_id = db.session.query(chartModel).filter(chartModel.id == '2024053114505639250008110').first()
    if exit_id is None:
        chartConfig = {}
        chartConfig["id"] = '2024053114505639250008110'
        chartConfig["name"] = '系统模板1'
        chartConfig["type"] = 1
        chartConfig["lessees_id"] = '000001'
        chartConfig["config"] = json.dumps(CHART01, ensure_ascii=False)
        db.session.add(chartModel(**chartConfig))
        db.session.commit()


def baseAddData(db):
    # 初始化创建经销商以及用户
    userAddData(db)
    # 初始化创建菜单
    barAddData(db)
    # 创建基础权限选项
    permissionAddData(db)
    # 创建基础数据类型
    basicTypeAddData(db)
    # 创建打印单据
    printOrderAddData(db)
    # 程序重启启动删除所有在线用户
    onLineModelDelete(db)
    # 增加定时任务配置
    timerTaskConfigModelAdd(db)
    # 初始化增加定时任务
    timerTaskModelAdd(db)
    # 初始化看板
    chartModelAdd(db)
    return
